/**
 * 解析树获取评分表数据结构
 * 1. 找到非叶子结点（目录）的行数，用来设置非叶子结点的评分和评分说明为readOnly
 * 2. 添加计算公式（需判断非叶子结点和叶子节点），公式不同
 * 3.二级节点三级节点等情况，既是目录又是其他目录子节点的情况，需要特殊处理
 * */ 
export const parseTreeData = (node, isShare, depth = 1) => {
  let result = [] // 表格数据
  let nonLeafLabels = [] // 非叶子结点label
  const traverse = (node, depth = 1) => {
    const level = `${depth}级`
    if (node.children && node.children.length > 0) {
      nonLeafLabels.push(node.label)
      node.children?.forEach(child => {
        // 最后位置加入一个id，方便后面查找
        result.push({
          isActive: false,
          isRoot: false,
          indicatorName: child.label,
          indicatorLevel: level,
          indicatorDes: child.tip,
          weight: child.weight + '%',
          scoreValue: '',
          scoreDes: '',
          totalScore: '',
          id: child.id
        })
        if (child.children) {
          traverse(child, depth + 1) // 递归处理子节点
        }
      })
    }
  }
  traverse(node, depth)
  // 找到非叶子结点的行数，用来设置非叶子结点的评分和评分说明为readOnly
  const nonLeafIndices = nonLeafLabels.map(label => result.findIndex(item => item['indicatorName'] === label)).filter(index => index !== -1)
  const cell = nonLeafIndices.map(item => [
    { row: item, col: 'scoreValue', readOnly: true },
    { row: item, col: 'scoreDes', readOnly: true }
  ]).flat()
  // 给非叶子结点添加isRoot属性
  result.forEach((item, index) => {
    if (nonLeafIndices.includes(index)) {
      item.isRoot = true
    }
  })
  // 添加计算公式（需判断非叶子结点）,根据目录的id查找到对应的子id，再根据子id查找对应的行数，最后定义目录的计算公式
  // nonLeafIndices.forEach((index) => {
  //   const ids = findDirectChildrenIds(node, result[index]['id'])
  //   const indexes = findIndexesByIds(result, ids)
  //   if (isShare) {
  //     result[index]['totalScore'] = `=SUM(${indexes.map(i => `G${i + 1}`).join(',')})*D${index + 1}`
  //   } else {
  //     result[index]['totalScore'] = `=SUM(${indexes.map(i => `F${i + 1}`).join(',')})*C${index + 1}`
  //   }
  // })

  // result.forEach((row, index) => {
  //   if (!nonLeafIndices.includes(index)) {
  //     if (isShare) {
  //       row['totalScore'] = `=D${index + 1} * E${index + 1}`
  //     }
  //     row['totalScore'] = `=C${index + 1} * D${index + 1}`
  //   }
  // })

  return { result, cell, nonLeafIndices }
}

// 根据id查找对应的子id
export function findDirectChildrenIds(tree, parentId) {
  // 定义一个函数来递归查找子节点  
  function recursiveSearch(node) {  
    // 如果当前节点的ID与给定的父ID匹配，则返回其子节点的ID数组  
    if (node.id === parentId) {  
      return node.children.map(child => child.id);  
    }  
    // 否则，递归检查每个子节点  
    if (node.children && node.children.length > 0) {
      for (const child of node.children) {  
        const result = recursiveSearch(child);  
        // 如果找到了匹配的子节点，则返回结果  
        if (result.length > 0) {  
          return result;  
        }  
      }  
    }
    // 如果没有找到匹配的子节点，则返回一个空数组  
    return [];  
  }  
  
  // 从根节点开始递归搜索  
  return recursiveSearch(tree);  
}

// 根据ids查找对应的行数
export function findIndexesByIds(result, ids) {
  const indexes = []
  for (const id of ids) {
    const index = result.findIndex(subArray => subArray['id'] === id)
    if (index !== -1) {
      indexes.push(index)
    }
  }
  return indexes
}

// 给小计添加计算公式
export function addTotalScoreFormula(treeData, result, nonLeafIndices, isShare) {
  nonLeafIndices.forEach((index) => {
    const ids = findDirectChildrenIds(treeData, result[index]['id'])
    const indexes = findIndexesByIds(result, ids)
    if (isShare) {
      result[index]['totalScore'] = `=SUM(${indexes.map(i => `G${i + 1}`).join(',')})*D${index + 1}`
    } else {
      result[index]['totalScore'] = `=SUM(${indexes.map(i => `F${i + 1}`).join(',')})*C${index + 1}`
    }
  })
  result.forEach((row, index) => {
    if (!nonLeafIndices.includes(index)) {
      if (isShare) {
        row['totalScore'] = `=D${index + 1} * E${index + 1}`
      } else {
        row['totalScore'] = `=C${index + 1} * D${index + 1}`
      }
    }
  })
  return result
}

// 根据列索引获取Excel中的字母，如：1->A,2->B
// const columnIndexToExcelColumn = (index) => {
//   let column = '';
//   let temp = index;
//   while (temp > 0) {
//     let remainder = (temp - 1) % 26;
//     column = String.fromCharCode(65 + remainder) + column;
//     temp = Math.floor((temp - 1) / 26);
//   }
//   return column;
// }